package customerController

import (
	"WEB/models"
	"fmt"
	"github.com/astaxie/beego/orm"
)

type ShopcartController struct {
	BaseController
}

// @router /customer/shopcart [get]
func (this *ShopcartController) GetPage() {
	user := this.GetSession("User").(models.User)
	userId := user.UserId
	newOrm := orm.NewOrm()
	var shops []models.ShopCard
	sql := models.QueryByEqualField(models.ShopCard{}, "ShopCardUserId")
	_, e := newOrm.Raw(sql, userId).QueryRows(&shops)
	if e != nil {
		panic(e)
	}
	for i, _ := range shops {
		shops[i].ShopCardGood = models.SelectAllFromGoodWherePrimaryKey(shops[i].ShopCardGoodId)
		shops[i].ShopSum = shops[i].ShopCardGood.GoodPrices * float64(shops[i].ShopCardNumber)
	}
	this.Data["ShopItems"] = shops
	this.TplName = "customer/shopcart.html"
}

// @router /customer/shopcart [post]
func (this *ShopcartController) PostPage() {
	/**
	如果商品存在
		修改购物车数量
	否则
		新建一个购物车项
	*/
	user := this.GetSession("User").(models.User)
	var shopCard models.ShopCard
	goodId, err := this.GetInt("goodId")
	if err != nil {
		panic(err)
	}
	shopNum, err := this.GetInt("shopNum")
	if err != nil {
		panic(err)
	}
	prices, err := this.GetFloat("prices")
	if err != nil {
		panic(err)
	}
	shopCard.ShopCardNumber = shopNum
	shopCard.ShopCardPrice = prices
	shopCard.ShopCardGoodId = goodId
	shopCard.ShopCardUserId = user.UserId

	newOrm := orm.NewOrm()
	var temp models.ShopCard
	sql := models.QueryByEqualField(shopCard, "ShopCardUserId", "ShopCardGoodId")
	err = newOrm.Raw(sql, shopCard.ShopCardUserId, shopCard.ShopCardGoodId).QueryRow(&temp)
	if err != nil {
		sql = models.InsertWithoutPrimaryKey(shopCard)
		_, e := newOrm.Raw(sql, models.GetFieldValue(shopCard, models.IsPrimaryKey)).Exec()
		if e != nil {
			panic(e)
		}
	} else {
		sql = models.UpdateFieldsByPrimary(temp, "ShopCardNumber")
		number := temp.ShopCardNumber + shopCard.ShopCardNumber
		_, err = newOrm.Raw(sql, number, temp.ShopCardId).Exec()
		if err != nil {
			panic(err)
		}
	}

	body := models.ResponseBody{
		0,
		"ok",
		nil,
	}
	this.Data["json"] = body
	this.ServeJSON()
}

// @router /customer/deleteShop [post]
func (this *SearchController) DeleteShop() {
	user := this.GetSession("User").(models.User)
	shopId, err := this.GetInt("shopId")
	if err != nil {
		panic(err)
	}
	newOrm := orm.NewOrm()
	var shopCart models.ShopCard
	sql := models.DeleteByField(shopCart, "ShopCardId", "ShopCardUserId")
	fmt.Println("delete", sql)
	newOrm.Raw(sql, shopId, user.UserId).Exec()
	this.Redirect("/customer/shopcart", 302)
}

// @router /customer/setCount [post]
func (this *SearchController) AddCount() {
	shopId, err := this.GetInt("shopId")
	if err != nil {
		panic(err)
	}
	count, err := this.GetInt("count")
	if err != nil {
		panic(err)
	}
	newOrm := orm.NewOrm()
	var shopCart models.ShopCard
	sql := models.UpdateFieldsByPrimary(shopCart, "ShopCardNumber")
	fmt.Println("update", sql)
	newOrm.Raw(sql, count, shopId).Exec()
	this.Redirect("/customer/shopcart", 302)
}
